//
//  ViewController.m
//  03-响应式编程思想
//
//  Created by J on 16/2/18.
//  Copyright © 2016年 J. All rights reserved.
//

#import "ViewController.h"
#import "NSObject+KVO.h"
#import "Person.h"
@interface ViewController ()
@property(nonatomic,strong)Person* person;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Person* person = [Person new];
    _person = person;
    //添加观察者
//    [_person addObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
        [_person xmgAddObserver:self forKeyPath:@"age" options:NSKeyValueObservingOptionNew context:nil];
    //1.只要p的age属性一改变,就会调用观察者的observeValueForKeyPath
    //KVO底层实现:
    //1.运行时动态创建NSKVONotifying_Person,NSKVONotifying_Person是Person子类做KVO
    //2.修改当前对象的isa指针 isa	-> NSKVONotifying_Person(NSKVONotifying_(+类名))
    //3.只要调用对象的set方法就会调用NSKVONotifying_Person的set方法
    //4.重写NSKVONotifying_Person的set方法1.[super set:]2.通知观察者属性值改变
    //就是判断有没有调用一个对象的set方法
    
    

}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    _person.age++;
//    _person->_age ++;//此处没有调用set方法就不会调用KVO的observeValueForKeyPath方法  (要把属性设置为@public)
//    NSLog(@"%zd",_person.age);
}

//监听的属性只要一改变就调用
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    NSLog(@"xxx%s %zd",__FUNCTION__,_person.age);
    
    
    
}


@end
